package com.xu.service;

import com.alibaba.fastjson.JSON;
import com.xu.mapper.MovieDetailMapper;
import com.xu.mapper.MovieMapper;
import com.xu.pojo.Movie;
import com.xu.uitls.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MovieService {
    @Autowired
    private MovieMapper movieMapper;
    @Autowired
    private MovieDetailMapper movieDetailMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Transactional
    public void saveMovie(Movie movie){
        if (movie.getName() == null)
            return;

        Movie result = movieMapper.queryMovieByName(movie.getName());

        //System.out.println(result);
        if (result == null){
            movieMapper.insertMovie(movie);
            int id = movie.getId();
            movie.getMovieDetail().setMovieId(id);
            redisTemplate.opsForList().rightPush("movies", JSON.toJSONString(movie));
            System.out.println(movie);
        } else {
            //修改
            movie.setId(result.getId());
            movieMapper.updateMovie(movie);
            redisTemplate.opsForList().rightPush("movies", JSON.toJSONString(movie));
            //System.out.println(movie);
            movie.setId(null);
        }


    }

    public List<Movie> queryMovies(String date){
        List<Object> movies = redisTemplate.opsForList().range("movies", 0, -1);
        List<Movie> movieList = new ArrayList<>();

        if (movies != null){
            for (Object item : movies) {
                Movie movie = JSON.parseObject((String) item, Movie.class);
                if (movie.getUpdateTime().compareTo(DateUtil.gainTime(new Date(new Date().getTime() - 1000 * 60 * 60))) > 0)
                    movieList.add(movie);
            }
            return movieList;
        }

        return movieMapper.queryMovies(date);
    }

    public Movie queryMovieById(int id){
        return movieMapper.queryMovieById(id);
    }
}
